<template>
  <div class="w-full">
    <!-- 统一的公共 Tab 组件 -->
    <UiTabGroup v-model="activeTab" :tabs="tabs" />

    <!-- Tab内容区域 -->
    <div class="w-full">
      <!-- 上传的影片 Tab -->
      <div v-show="activeTab === 'movies'" class="animate-fade-in">
        <div class="flex items-center justify-between mb-6">
          <h3 class="text-xl font-bold text-text-primary">{{ tabs.find(t => t.id === 'movies')?.label }}</h3>
          <div class="flex items-center gap-4">
            <span class="text-sm text-text-muted">{{ userStats.movieCount }} 部影片</span>
            <UiButton
              v-if="isCurrentUser"
              @click="$router.push('/upload-movie')"
              variant="primary"
              size="sm"
            >
              上传新影片
            </UiButton>
          </div>
        </div>
        
        <div v-if="isLoadingMovies" class="flex justify-center py-12">
          <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500"></div>
        </div>
        
        <div v-else-if="movies.length > 0" class="w-full">
          <!-- 瀑布流布局 -->
          <div :class="`movie-grid gap-4 ${gridColsClass}`">
            <div
              v-for="movie in movies"
              :key="movie.id"
              class="relative group"
            >
              <!-- 影片卡片 -->
              <MovieCard
                :cover-url="movie.coverUrl"
                :title="movie.title"
                :rating="movie.rating"
                :tags="movie.tags"
                :is-ai="movie.isAi"
                :show-tags="true"
                @click="goDetail(movie.id)"
              />
              
              <!-- 管理按钮 - 仅当前用户可见 -->
              <div v-if="isCurrentUser" class="absolute top-2 right-2 opacity-100 transition-opacity duration-200 z-10">
                <div class="flex gap-1">
                  <!-- 编辑按钮 -->
                  <UiButton
                    @click.stop="editMovie(movie.id)"
                    variant="primary"
                    size="sm"
                    shape="circle"
                    title="编辑影片"
                  >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                  </UiButton>
                  
                  <!-- 删除按钮 -->
                  <UiButton
                    @click.stop="confirmDeleteMovie(movie)"
                    variant="danger"
                    size="sm"
                    shape="circle"
                    title="删除影片"
                  >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </UiButton>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 加载更多按钮 -->
          <div v-if="hasMoreMovies && !isLoadingMovies" class="flex justify-center mt-8">
            <UiButton
              @click="loadMoreMovies"
              variant="primary"
            >
              加载更多
            </UiButton>
          </div>
        </div>
        
        <div v-else class="text-center py-16 text-text-muted">
          <div class="text-lg mb-2">暂无上传的影片</div>
          <div class="text-sm">{{ isCurrentUser ? '你还没有上传任何虚构电影' : '这个用户还没有上传任何虚构电影' }}</div>
          <div v-if="isCurrentUser" class="mt-4">
            <UiButton
              @click="$router.push('/upload-movie')"
              variant="primary"
            >
              上传第一部影片
            </UiButton>
          </div>
        </div>
      </div>

      <!-- 评论 Tab -->
      <div v-show="activeTab === 'comments'" class="animate-fade-in">
        <div class="flex items-center justify-between mb-6">
          <h3 class="text-xl font-bold text-text-primary">{{ tabs.find(t => t.id === 'comments')?.label }}</h3>
          <span class="text-sm text-text-muted">{{ userStats.commentCount }} 条评论</span>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="isLoadingComments" class="flex justify-center py-12">
          <div class="text-text-muted">加载中...</div>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="commentsError" class="text-center py-8">
          <div class="text-error mb-4">{{ commentsError }}</div>
          <UiButton 
            @click="loadUserComments"
            variant="primary"
          >
            重试
          </UiButton>
        </div>

        <!-- 评论列表 -->
        <div v-else-if="comments.length > 0" class="space-y-4">
          <UserCommentCard 
            v-for="comment in comments" 
            :key="comment.id" 
            :comment="comment"
            :canDelete="isCurrentUser"
            @delete="handleDeleteComment"
          />
        </div>

        <!-- 空状态 -->
        <div v-else class="text-center py-16 text-text-muted">
          {{ isCurrentUser ? '你还没有发表过评论' : '这个用户还没有发表过评论' }}
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteDialog" class="fixed inset-0 bg-background-900/50 flex items-center justify-center z-50">
      <div class="bg-background-800 rounded-lg p-6 max-w-md w-full mx-4">
        <h3 class="text-lg font-semibold text-text-primary mb-4">确认删除</h3>
        <p class="text-text-secondary mb-6">
          确定要删除影片 "{{ movieToDelete?.title }}" 吗？此操作无法撤销。
        </p>
        <div class="flex gap-3 justify-end">
          <UiButton
            @click="showDeleteDialog = false"
            variant="secondary"
          >
            取消
          </UiButton>
          <UiButton
            @click="deleteMovie"
            variant="danger"
            :loading="isDeletingMovie"
          >
            删除
          </UiButton>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../../store/useUserStore'
import { useUserData } from '../../composables/useUserData'
import { useMovieLoader } from '../../composables/movies'
import { useUiStore } from '../../store/useUiStore'
import { storeToRefs } from 'pinia'
import { supabase } from '../../lib/supabase'
import type { Comment } from '../../types/ui'
  import { UiButton, UiTabGroup } from '../ui/index'
import MovieCard from '../movie/MovieCard.vue'
import UserCommentCard from './UserCommentCard.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const { getUserComments, getUserStats } = useUserData()
const { loadUserMovies } = useMovieLoader()
const uiStore = useUiStore()
const { gridColsClass } = storeToRefs(uiStore)

// Props
interface Props {
  userId: string
}

const props = defineProps<Props>()

// 数据状态
const movies = ref<any[]>([])
const comments = ref<Comment[]>([])
const isLoadingMovies = ref(false)
const isLoadingComments = ref(false)
const commentsError = ref<string | null>(null)
const hasMoreMovies = ref(true)
const currentMovieOffset = ref(0)
const userStats = ref({ movieCount: 0, commentCount: 0 })
const activeTab = ref('movies')

// 删除相关状态
const showDeleteDialog = ref(false)
const movieToDelete = ref<any>(null)
const isDeletingMovie = ref(false)

// 计算属性：判断是否为当前用户
const isCurrentUser = computed(() => {
  if (!userStore.isAuthenticated) return false
  const currentUserId = userStore.userId
  const pageUserId = props.userId
  return currentUserId === pageUserId
})

// Tab配置
const tabs = computed(() => [
  {
    id: 'movies',
    label: isCurrentUser.value ? '我的影片' : '上传的影片',
    count: userStats.value.movieCount
  },
  {
    id: 'comments',
    label: isCurrentUser.value ? '我的评论' : '评论',
    count: userStats.value.commentCount
  }
])

// 电影相关方法
const goDetail = (id: number) => {
  router.push({ name: 'MovieDetail', params: { id } })
}

const editMovie = (id: number) => {
  router.push({ name: 'EditMovie', params: { id } })
}

const confirmDeleteMovie = (movie: any) => {
  movieToDelete.value = movie
  showDeleteDialog.value = true
}

const deleteMovie = async () => {
  if (!movieToDelete.value || !isCurrentUser.value) return
  
  isDeletingMovie.value = true
  
  try {
    // 验证权限
    const { data: movieData, error: fetchError } = await supabase
      .from('movies')
      .select('uploader_id')
      .eq('id', movieToDelete.value.id)
      .single()

    if (fetchError) {
      throw new Error('影片不存在')
    }

    if (movieData.uploader_id !== userStore.userId) {
      throw new Error('您没有权限删除此影片')
    }

    // 删除影片
    const { error: deleteError } = await supabase
      .from('movies')
      .delete()
      .eq('id', movieToDelete.value.id)

    if (deleteError) {
      throw deleteError
    }

    // 从本地列表中移除
    movies.value = movies.value.filter(m => m.id !== movieToDelete.value.id)
    
    // 更新统计信息
    await loadUserStats()
    
    // 关闭对话框
    showDeleteDialog.value = false
    movieToDelete.value = null
    
  } catch (err) {
    console.error('Error deleting movie:', err)
    uiStore.showError(err instanceof Error ? err.message : '删除影片失败')
  } finally {
    isDeletingMovie.value = false
  }
}

const loadUserMoviesData = async (userId: string, isLoadMore = false) => {
  if (isLoadMore) {
    if (isLoadingMovies.value || !hasMoreMovies.value) return
  } else {
    isLoadingMovies.value = true
    currentMovieOffset.value = 0
  }
  
  try {
    const userMovies = await loadUserMovies(userId, 12, currentMovieOffset.value)
    
    if (isLoadMore) {
      movies.value.push(...userMovies)
    } else {
      movies.value = userMovies
    }
    
    hasMoreMovies.value = userMovies.length === 12
    currentMovieOffset.value += userMovies.length
  } catch (err) {
    console.error('Error loading user movies:', err)
  } finally {
    isLoadingMovies.value = false
  }
}

const loadMoreMovies = async () => {
  const userId = props.userId
  if (userId) {
    await loadUserMoviesData(userId, true)
  }
}

// 评论相关方法
const loadUserComments = async () => {
  const userId = props.userId
  if (!userId) return

  isLoadingComments.value = true
  commentsError.value = null
  
  try {
    const userComments = await getUserComments(userId, 20, 0)
    comments.value = userComments
  } catch (err) {
    console.error('Error loading user comments:', err)
    commentsError.value = '加载评论失败'
  } finally {
    isLoadingComments.value = false
  }
}

const handleDeleteComment = async (commentId: number) => {
  console.log('UserContent: Attempting to delete comment:', commentId)
  console.log('UserContent: Current user:', userStore.userId)
  console.log('UserContent: Page user:', route.params.id)
  console.log('UserContent: Is current user:', isCurrentUser.value)
  
  // 只有当前用户才能删除评论
  if (!isCurrentUser.value) {
    commentsError.value = '非当前用户，无法删除评论'
    console.warn('UserContent: Permission denied: not current user')
    return
  }

  try {
    // 首先验证评论是否属于当前用户
    console.log('UserContent: Fetching comment data for verification...')
    const { data: commentData, error: fetchError } = await supabase
      .from('comments')
      .select('user_id')
      .eq('id', commentId)
      .single()

    if (fetchError) {
      console.error('UserContent: Error fetching comment:', fetchError)
      throw new Error('评论不存在')
    }

    console.log('UserContent: Comment data:', commentData)
    console.log('UserContent: Comment user ID:', commentData.user_id)
    console.log('UserContent: Current user ID:', userStore.userId)

    // 再次确认权限
    if (commentData.user_id !== userStore.userId) {
      commentsError.value = '您没有权限删除此评论'
      console.warn('UserContent: Permission denied: comment does not belong to current user')
      return
    }

    console.log('UserContent: Permission verified, proceeding with deletion...')
    const { error: deleteError } = await supabase
      .from('comments')
      .delete()
      .eq('id', commentId)

    if (deleteError) {
      console.error('UserContent: Error deleting comment:', deleteError)
      throw deleteError
    }

    console.log('UserContent: Comment deleted successfully')
    // 从本地列表中移除
    comments.value = comments.value.filter(c => c.id !== commentId)
    
    // 更新统计信息
    await loadUserStats()
    
    // 清除错误信息
    commentsError.value = null
  } catch (err) {
    console.error('UserContent: Error deleting comment:', err)
    commentsError.value = err instanceof Error ? err.message : '删除评论失败'
  }
}

// 加载用户统计信息
const loadUserStats = async () => {
  const userId = props.userId
  if (userId) {
    try {
      const stats = await getUserStats(userId)
      userStats.value = stats
    } catch (error) {
      console.error('Error loading user stats:', error)
    }
  }
}

// 初始化数据加载函数
const initializeData = async (userId: string) => {
  // 重置状态
  movies.value = []
  comments.value = []
  currentMovieOffset.value = 0
  hasMoreMovies.value = true
  isLoadingMovies.value = false
  isLoadingComments.value = false
  commentsError.value = null
  
  // 并行加载所有数据
  await Promise.all([
    loadUserMoviesData(userId),
    loadUserComments(),
    loadUserStats()
  ])
}

// 监听props变化
watch(() => props.userId, async (newUserId) => {
  if (newUserId) {
    await initializeData(newUserId)
  }
}, { immediate: true })

// 初始化
onMounted(async () => {
  const userId = props.userId
  if (userId) {
    await initializeData(userId)
  }
})
</script> 